//
//  WNetworkTool.swift
//  DanTang
//
//  Created by mnine on 18/3/24.
//  Copyright © 2018年 hrscy. All rights reserved.
//

import UIKit
import Alamofire
import SVProgressHUD
import SwiftyJSON
import SwiftKeychainWrapper

class WNetwork: NSObject {
    /// 单例  相当于实例化一个该类？
    static let shareNetworkTool = WNetwork()
    /// BASE_URL http://www.china-ofdi.org/
    
    /// sid 种类 22 轮播新闻 get  "/api/hotnews/5"        2    catid＝30
    func loadLunBo(finished:@escaping (_ hotnews5: [WZiXun]) -> ()) {
        // let url = BASE_URL + "api/hotnews/5"
        let url = BASE_URL + "api/hotnews/5"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "加载失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok
                    guard status == RETURN_OK else {
                        SVProgressHUD.showInfo(withStatus: msg)
                        return
                    }
                    SVProgressHUD.dismiss()
                    //  data 为数组形式
                    if let items = dict["data"].arrayObject {
                        var hotnews5 = [WZiXun]()
                        for item in items {
                            let news = WZiXun(dict: item as! [String: AnyObject])
                            hotnews5.append(news)
                        }
                        finished(hotnews5)
                    }
                }
        }
    }
    
    /// sid 种类 21 各类资讯 get  "/apin/zx/\(catid)"     300  catid＝39－展会公告 30-带图新闻 31-行业资讯（8）
    func loadMZixun(catid: Int,finished:@escaping (_ mzixuns: [WZiXun]) -> ()) {
        let url = BASE_URL + "apin/zx/\(catid)"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "加载失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok
                    guard status == RETURN_OK else {
                        SVProgressHUD.showInfo(withStatus: msg)
                        return
                    }
                    SVProgressHUD.dismiss()
                    //  data 为数组形式
                    if let items = dict["data"].arrayObject {
                        var mzixuns = [WZiXun]()
                        for item in items {
                            let news = WZiXun(dict: item as! [String: AnyObject])
                            mzixuns.append(news)
                        }
                        finished(mzixuns)
                    }
                }
        }
    }
    /// sid 种类 22 合作伙伴 get  "/apin/hbzx/\(catid)"   2    catid＝21－各国投资促进机构 22－基金 23－商业和行业协会 24－其他
    func loadHBZixun(catid: Int,finished:@escaping (_ hbzixun2: [WZiXun]) -> ()) {
        let url = BASE_URL + "apin/hbzx/\(catid)"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "加载失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok
                    guard status == RETURN_OK else {
                        SVProgressHUD.showInfo(withStatus: msg)
                        return
                    }
                    //  data 为数组形式
                    if let items = dict["data"].arrayObject {
                        var hbzixun2 = [WZiXun]()
                        for item in items {
                            let news = WZiXun(dict: item as! [String: AnyObject])
                            hbzixun2.append(news)
                        }
                        finished(hbzixun2)
                    }
                }
        }
    }
    
    
    /// sid 种类 1 首推项目  get   "/apin/recommend_pro"  5
    func loadCommond(finished:@escaping (_ commond5: [WPro]) -> ()) {
        let url = BASE_URL + "apin/recommend_pro"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "加载失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok
                    guard status == RETURN_OK else {
                        SVProgressHUD.showInfo(withStatus: msg)
                        return
                    }
                    SVProgressHUD.dismiss()
                    //  data 为数组形式
                    if let items = dict["data"].arrayObject {
                        var commond5 = [WPro]()
                        for item in items {
                            let dan = WPro(dict: item as! [String: AnyObject])
                            commond5.append(dan)
                        }
                        finished(commond5)
                    }
                }
        }
    }
    
    
    /// sid 种类 11各类项目  get   "/apin/pro/\(catid)"   list 280ge
    /// 1-海外投资 2-基础设施 4-境外园区 5-国际产能 6-海外安保 7-人才培训 37-法律服务 38-审计服务 40-咨询服务 43-招投标信息 44-翻译服务
    func loadMPro(catid: Int,finished:@escaping (_ mpros: [WPro]) -> ()) {
        let url = BASE_URL + "apin/pro/\(catid)"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "加载失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok
                    guard status == RETURN_OK else {
                        SVProgressHUD.showInfo(withStatus: msg)
                        return
                    }
                    SVProgressHUD.dismiss()
                    //  data 为数组形式
                    if let items = dict["data"].arrayObject {
                        if items.isEmpty {
                            SVProgressHUD.showInfo(withStatus: "这里空空如也！暂无任何项目！")
                        }
                        var mpros = [WPro]()
                        for item in items {
                            let dan = WPro(dict: item as! [String: AnyObject])
                            mpros.append(dan)
                        }
                        finished(mpros)
                    }
                }
        }
    }

    
    /// sid 种类 2 国别项目  get   "/apin/search/\(key)"  限定key为各个国家list 给出国家列表
    /// sid 种类 2 寻找项目  get   "/apin/search/\(key)"  300  title or filterattr_value
    func loadSearch(key: String,finished:@escaping (_ spros: [WPro]) -> ()) {
        let murl = BASE_URL + "apin/search/\(key)"
        let url = murl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        Alamofire
            .request(url!)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    print("\(key)")
                    SVProgressHUD.showError(withStatus: "加载失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok
                    guard status == RETURN_OK else {
                        SVProgressHUD.showInfo(withStatus: msg)
                        return
                    }
                    SVProgressHUD.dismiss()
                    //  data 为数组形式
                    if let items = dict["data"].arrayObject {
                        if items.isEmpty {
                            SVProgressHUD.showInfo(withStatus: "这里空空如也！")
                        }
                        var spros = [WPro]()
                        for item in items {
                            let dan = WPro(dict: item as! [String: AnyObject])
                            spros.append(dan)
                        }
                        finished(spros)
                    }
                }
        }
    }
    
    
    /// sid 种类 3 热门项目  get   "/apin/hot_pro"        250
    /// sid 种类 4 最新项目  get   "/apin/latest_pro"     250
    func loadHotPro(finished:@escaping (_ hotpros: [WPro]) -> ()) {
        let url = BASE_URL + "apin/hot_pro"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "加载失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok
                    guard status == RETURN_OK else {
                        SVProgressHUD.showInfo(withStatus: msg)
                        return
                    }
                    SVProgressHUD.dismiss()
                    //  data 为数组形式
                    if let items = dict["data"].arrayObject {
                        var hotpros = [WPro]()
                        for item in items {
                            let dan = WPro(dict: item as! [String: AnyObject])
                            hotpros.append(dan)
                        }
                        finished(hotpros)
                    }
                }
        }
    }
    func loadLatPro(finished:@escaping (_ latpros: [WPro]) -> ()) {
        let url = BASE_URL + "apin/latest_pro"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "加载失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok
                    guard status == RETURN_OK else {
                        SVProgressHUD.showInfo(withStatus: msg)
                        return
                    }
                    //  data 为数组形式
                    if let items = dict["data"].arrayObject {
                        var latpros = [WPro]()
                        for item in items {
                            let dan = WPro(dict: item as! [String: AnyObject])
                            latpros.append(dan)
                        }
                        finished(latpros)
                    }
                }
        }
    }
    
    /// MARK : 收藏 发布
    /// sid 种类 5 收藏某项  post  "/apin/collectcreate"  参数：(user_id) (pro_id)
    /// sid 种类 6 已收藏项  get   “/apin/{user_id}/collectlist”
    /// sid 种类 7 取消收藏  get   "/apin/collectdestroy/\(user_id)/\(pro_id)"
    /// sid 种类 8 查收藏项  get   “/apin/collectlistsearch/\(user_id)/\(key)”
    /// sid 种类 9 发布项目  post  "/apin/procreate"      参数：
    /// 参数：id（不需要） uid catid（列表） title description filterattr_value（地域丨行业丨方式） amount_money  content
    /// sid 种类 10已发布项  get   “/apin/\(uid)/createlist”
    func shoucangPro(user_id: Int,pro_id: Int){
        let url = BASE_URL + "apin/collectcreate"
        let params = ["user_id": user_id,
                      "pro_id": pro_id] as [String : Any]
        Alamofire
            .request(url, method: .post, parameters: params)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "收藏失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let msg = dict["msg"].stringValue
                    SVProgressHUD.showInfo(withStatus: msg)
                }
        }
    
    }
    func qxshoucangPro(user_id: Int,pro_id: Int){
        let url = BASE_URL + "apin/collectdestroy/\(user_id)/\(pro_id)"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "取消收藏失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let msg = dict["msg"].stringValue
                    SVProgressHUD.showInfo(withStatus: msg)
                }
        }
        
    }
    func hadshoucangPro(user_id: Int,finished:@escaping (_ hadscpros: [WPro]) -> ()) {
        let url = BASE_URL + "apin/\(user_id)/collectlist"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "加载失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok buzhixinglimian
                    guard status == RETURN_OK else {
                        SVProgressHUD.showInfo(withStatus: msg)
                        return
                    }
                    SVProgressHUD.dismiss()
                    //  data 为数组形式 可能为nil 注意
                    if let items = dict["data"].arrayObject {
                        if items.isEmpty {
                            SVProgressHUD.showInfo(withStatus: "这里空空如也！您还没有收藏任何项目！")
                        }
                        var hadscpros = [WPro]()
                        for item in items {
                            let dan = WPro(dict: item as! [String: AnyObject])
                            hadscpros.append(dan)
                        }
                        finished(hadscpros)
                    }
                }
        }
    }
    func createPro(uid: Int,catid: Int,title: String,description: String,filterattr_value: String,amount_money: Int,content: String,finished:@escaping (_ msg: String) -> ()) {
        /// 参数：id（不需要） uid catid（列表） title description filterattr_value（地域丨行业丨方式） amount_money  content
        let url = BASE_URL + "apin/procreate"
        let params = ["uid": uid,
                      "title": title,
                      "catid": catid,
                      "description": description,
                      "filterattr_value": filterattr_value,
                      "amount_money": amount_money,
                      "content": content] as [String : Any]
        Alamofire
            .request(url, method: .post, parameters: params)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "发布失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok
                    if status == RETURN_OK {
                        SVProgressHUD.showInfo(withStatus: msg)
                    }
                    finished(msg)
                }
        }
    }
    func hadfabuPro(uid: Int,finished:@escaping (_ hadfbpros: [WPro]) -> ()) {
        let url = BASE_URL + "apin/\(uid)/createlist"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "加载失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok buzhixinglimian
                    guard status == RETURN_OK else {
                        SVProgressHUD.showInfo(withStatus: msg)
                        return
                    }
                    //  data 为数组形式 可能为nil 注意
                    if let items = dict["data"].arrayObject {
                        if items.isEmpty {
                            SVProgressHUD.showInfo(withStatus: "这里空空如也！您还没有发布任何项目！")
                        }
                        var hadfbpros = [WPro]()
                        for item in items {
                            let dan = WPro(dict: item as! [String: AnyObject])
                            hadfbpros.append(dan)
                        }
                        finished(hadfbpros)
                    }
                }
        }
    }
    
    
    
    /// sid 种类 27 个人信息查 get  “/apin/get_info/\(user_id)”
    /// sid 种类 28 个人信息改 post “/apin/update_info”   参数：
    func loadPerson(user_id: Int,finished:@escaping (_ msg: String) -> ()) {
        let url = BASE_URL + "apin/get_info/\(user_id)"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "加载失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok
                    guard status == RETURN_OK else {
                        SVProgressHUD.showError(withStatus: "网络加载失败...")
                        return
                    }
                    if status == 1 {
                        wname = dict["name"].stringValue
                        wemail = dict["email"].stringValue
                        wprovince = dict["province"].stringValue
                        wcity = dict["city"].stringValue
                        waddress = dict["address"].stringValue
                        wcompany_name = dict["company_name"].stringValue
                        finished(msg)
                    }
                }
        }
    }
    // hasEmail＝true，不能编辑，写不写入email都无所谓；hasEmail＝false，没有邮箱，写上邮箱，进入判断是否已经存在，没存在，可以保存，若存在过，返回邮箱已被注册过！
    func updatePerson(hasemail: Bool,user_id: Int,name: String,email: String,province: String,city: String,company_name: String,address: String) {
        let url = BASE_URL + "apin/update_info"
        let params = ["hasemail": hasemail,
                      "user_id": user_id,
                      "name": name,
                      "email": email,
                      "city": city,
                      "company_name": company_name,
                      "address": address,
                      "province": province] as [String : Any]
        Alamofire
            .request(url, method: .post, parameters: params)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "修改失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    if status == 1 {
                        let msg = dict["msg"].stringValue
                        wname = name
                        wemail = email
                        wprovince = province
                        wcity = city
                        KeychainWrapper.standard.set(name, forKey:"rname")
                        NotificationCenter.default.post(name:notifyNameMsgRecv, object: nil, userInfo: nil)
                        SVProgressHUD.showInfo(withStatus: msg)
                    }else {
                        SVProgressHUD.showInfo(withStatus: "提交失败，该邮箱已经被注册过！")
                    }
                }
        }
    }
    
    
    /// sid 种类 25 手机注册找回 get  “/apin/registerm/\(username)/\(password)/\(name)”
    /// sid 种类 26 邮箱注册 post  “/apin/email”        参数：email password name
    /// sid 种类 27 邮箱找回 post  “/apin/findemail”    参数：email password
    
    
    
    
    /// sid 种类 29 用户留言 post  “/apin/feedback”     参数：
    
    //    $name=$request->name;
    //    $company_name="";
    //    $phone=$request->phone;   ///联系方式：电话或者邮箱
    //    $contact=$request->contact;
    //    $message=$request->message;
    func LiuYan(name: String,phone: String,contact: String,content: String,finished:@escaping (_ msg: String) -> ()) {
        let url = BASE_URL + "apin/feedback"
        let params = ["name": name,
                      "phone": phone,
                      "contact": contact,
                      "message": content] as [String : Any]
        Alamofire
            .request(url, method: .post, parameters: params)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "发布失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok
                    if status == RETURN_OK {
                        SVProgressHUD.showInfo(withStatus: msg)
                    }
                    finished(msg)
                }
        }
    }
    /// sid 种类 30 版本检查 get   “”
    /// sid 种类 24 试图登录 get 用户名和密码  “”
    func tryLogin(username: String,password: String) {
        let url = BASE_URL + "apin/user/login/\(username)/\(password)"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "登录失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    print(msg,status)
                    SVProgressHUD.showInfo(withStatus: msg)
                    let data = JSON(dict["data"].arrayValue)
                    //let data1 = JSON
                    if status == 1 {
                        whaslogin = true
                        wname = data["name"].stringValue
                        wemail = data["email"].stringValue
                        wprovince = data["province"].stringValue
                        wcity = data["city"].stringValue
                        waddress = data["address"].stringValue
                        wcompany_name = data["company_name"].stringValue
                        print(whaslogin!)
                    }
                }
        }
    }
    
    // 热搜
    func loadHotWords(finished:@escaping (_ words: [String]) -> ()) {
        SVProgressHUD.show(withStatus: "正在加载...")
        let url = BASE_URL + "apin/version"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "加载失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let words = dict["words"].arrayObject
                    print(words ?? 0)
                    SVProgressHUD.dismiss()
                    finished(words as! [String])
                }
        }
    }
    
    func emailCode(email: String,code: String) {
        let url = BASE_URL + "apin/ios/emailcode/post"
        let params = ["email": email,
                      "code": code] as [String : Any]
        Alamofire
            .request(url, method: .post, parameters: params)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "发送失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok
                    guard status == 1 else {
                        SVProgressHUD.showError(withStatus: msg)
                        return
                    }
                    SVProgressHUD.showSuccess(withStatus: msg)
                }
        }
    }
    
    func randomIn(min: Int, max: Int) -> Int {
        return Int(arc4random()) % (max - min + 1) + min
    }
    
    
    // 咨询
    func shoucangZX(user_id: Int,zxc_id: Int){
        let url = BASE_URL + "apin/ios/zx/collect"
        let params = ["user_id": user_id,
                      "zx_id": 0,
                      "zxc_id": zxc_id] as [String : Any]
        Alamofire
            .request(url, method: .post, parameters: params)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "操作失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let msg = dict["msg"].stringValue
                    SVProgressHUD.showInfo(withStatus: msg)
                }
        }
    }
    func zanZX(user_id: Int,zx_id: Int){
        let url = BASE_URL + "apin/ios/zx/zan"
        let params = ["user_id": user_id,
                      "zxc_id": 0,
                      "zx_id": zx_id] as [String : Any]
        Alamofire
            .request(url, method: .post, parameters: params)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "操作失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let msg = dict["msg"].stringValue
                    SVProgressHUD.showInfo(withStatus: msg)
                }
        }
        
    }
    
    func loadMSCZixun(user_id: Int,finished:@escaping (_ mzixuns: [WZiXun]) -> ()) {
        let url = BASE_URL + "apin/ios/zx/mycollect/\(wuserid!)"
        Alamofire
            .request(url)
            .responseJSON { (response) in
                guard response.result.isSuccess else {
                    SVProgressHUD.showError(withStatus: "加载失败...")
                    return
                }
                if let value = response.result.value {
                    let dict = JSON(value)
                    let status = dict["status"].intValue
                    let msg = dict["msg"].stringValue
                    // RETURN_OK: 1  msg: ok
                    guard status == RETURN_OK else {
                        SVProgressHUD.showInfo(withStatus: msg)
                        return
                    }
                    SVProgressHUD.dismiss()
                    //  data 为数组形式
                    if let items = dict["data"].arrayObject {
                        var mzixuns = [WZiXun]()
                        for item in items {
                            let news = WZiXun(dict: item as! [String: AnyObject])
                            mzixuns.append(news)
                        }
                        finished(mzixuns)
                    }
                }
        }
    }
    
}
